import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../main.dart';

class CommonUtil {
  static void storeUserInfo(String username, String password, int id) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString("username", username);
    prefs.setString("password", password);
    prefs.setInt("id", id);
    prefs.setBool("isLogin", true);
  }

  static void removeUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove("username");
    prefs.remove("password");
    prefs.remove("id");
    prefs.remove("isLogin");
  }

  static Future<String> getUsername() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString("username") ?? "";
  }

  // static void jumpToPageByBuildContext(BuildContext context, Widget page) {
  //   Navigator.of(context).push(MaterialPageRoute(builder: (context) => page));
  // }
  //
  // static void jumpToPageByNavigatorState(Widget page) {
  //   NavigatorState? navigatorState = MyApp.navigatorKey.currentState;
  //   navigatorState?.push(MaterialPageRoute(builder: (context) => page));
  // }

  static void jumpToPageByPageName(BuildContext context, String pageName, [dynamic arguments]) {
    Navigator.of(context).pushNamed(pageName, arguments: arguments);
  }

  static void jumpToPageByNavigatorState(String pageName, [dynamic arguments]) {
    NavigatorState? navigatorState = MyApp.navigatorKey.currentState;
    navigatorState?.pushNamed(pageName, arguments: arguments);
  }

  static Future<bool> isLogin(BuildContext context, bool needJumpToLogin) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool("isLogin") ?? false;
  }

  static PersistCookieJar? _cookieJar;

  static Future<PersistCookieJar> getCookieJar() async {
    if (_cookieJar == null) {
      Directory appDirectory = await getApplicationDocumentsDirectory();
      String appDirectoryPath = appDirectory.path;
      debugPrint('获取的文件系统目录 appDirectoryPath：$appDirectoryPath');
      _cookieJar = PersistCookieJar(storage: FileStorage("$appDirectoryPath/.cookies/"));
    }
    return _cookieJar!;
  }
}
